import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

public class DataDivider {
	
    static HashMap<String, String[]> getHash(File file) throws IOException{
	String line = null;
	BufferedReader input = new BufferedReader(new FileReader(file));
	String[] coords;
	HashMap<String, String[]> hash = new HashMap<String, String[]>();
	while ( ( line = input.readLine() ) != null ) {
		coords = new String[2];
	    String fields[] = line.split("\t");
	    if ( fields.length != 3) continue;
	    coords[0]= fields[1];
	    coords[1]= fields[2];
	    hash.put(fields[0], coords);
	}
	return hash;
   }

   public static void main(String[] args) throws Exception {
    File textData = new File(args[0]);
    File coorData = new File(args[1]);
    File testData = new File(args[2]);
    File trainData = new File(args[3]);
    int trainNum = Integer.parseInt(args[4]);
    int testNum = Integer.parseInt(args[5]);
    String line = null;
    HashMap<String, String[]> hash = getHash(coorData);
    BufferedReader input = new BufferedReader(new FileReader(textData));
    FileWriter outputTest = new FileWriter(testData);
    FileWriter outputTrain = new FileWriter(trainData); 
    int it = 0;
    List<String> document = new ArrayList<String>();
    while ( ( line = input.readLine() ) != null ) {
	    String fields[] = line.split("\t");
	    if ( hash.get(fields[0]) == null) continue;
	    document.add(line); 	    
	    it++;
	}
	
	java.util.Collections.shuffle(document, new Random(2));
	
	for(int i= 0; i<it; i++){
		String field[] = document.get(i).split("\t");
		if(i < testNum){
			
			outputTest.write(field[0] + '\t' + field[1]);
			outputTest.write('\n');
			}
		else{ 
			if(i<(trainNum + testNum)){

			outputTrain.write(field[0] + '\t' + field[1]);	
			outputTrain.write('\n');
			}}
	}
	
	
	
	
	outputTest.close();
	outputTrain.close();
	
}



}
